﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using EntityBinder.Interface;

namespace EntityBinder.Json
{
	class JsonWriter : IEntityWriter
	{
		public bool Indent { get; set; }

		private IEntityElement m_rootElement = null;

		internal JsonWriter()
		{
			Indent = false;
		}

		internal JsonWriter(IEntityElement _rule) : this()
		{
			m_rootElement = _rule;
		}

		public void Write(System.IO.Stream _outputStream, object _data)
		{
			Write(_outputStream, _data, m_rootElement);
		}

		public void Write(System.IO.Stream _outputStream, object _data, IEntityElement _rules)
		{
			if(_rules == null)
			{
				throw new EntityBinderException("JsonWriter", "Write", "Can not write object without any rules");
			}

			//write to json file
			using (StreamWriter sw = new StreamWriter(_outputStream))
			{
				using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
				{
					if(Indent)
					{
						writer.Formatting = Newtonsoft.Json.Formatting.Indented;
					}
					writer.WriteStartObject();

					IElementWriter wr = new JsonElementWriter(writer);
					foreach(IEntityElement rule in _rules.Children)
					{
						rule.Write(_data, wr);
					}

					writer.WriteEndObject();
				}
			}
		}
	}
}
